// pages/user/shopingCart/shopingCart.js
//集成appjs中方法及属性
var Http = require('../../service/http.js'); //请求类
var Util = require('../../utils/util.js'); //工具类
const app = getApp();
var rd_session = wx.getStorageSync('rd_session');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //----------登录操作-----------------
    showLogin: false, //展示登录页
    pageUrl: '', //跳转地址
    productItems: "",
    pTitle: '',
    isEdit: false,
    isChecked: false,
    isCheckedAll: false,
    cartProducts: [], //购物车所有商品列表
    product: {},
    productId: '', //商品itemid
    isAuthorization: '', //是否已授权
    //----------暂存购物车商品信息-------------------
    itemId: '', //暂存购物车商品id 
    skuId: '', //skuid
    count: 1, //购物车数量
    stock: 0, //默认库存
    //---------购物车编辑操作------------------------
    totalCount: 0, //商品总额
    onProducts: [], //被选中的商品（用于计算总数额）
    selectNum: 0, //被选中商品数量
    compareNum: 0, //用于比较购物车数量的库存
    //---------店铺信息-----------------------------
    shopName: '', //店铺名称
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {
    wx.showTabBar();
  },
  //初始化数据
  dataInit: function() {
    this.setData({
      isAuthorization: app.data.isAuthorization,
      isEdit: false,
      isChecked: false,
      isCheckedAll: false,
      selectNum: 0, //被选中商品数量
      totalCount: 0, //商品总额
    })
  },
  onShow: function() {
    

      this.showCartList(); //加载购物车列表

   this.dataInit(); //初始化数据
  },
  //------------加载购物车列表----------------------------
  showCartList: function() {
    //请求购物车数据
    Http.getReq('/weixin/cart/showCartList', {
      rdSession: wx.getStorageSync('rd_session')
    }, (res)=> {
      console.log('showCartList', res);
      if (res.ret) {
        let cartProducts = res.data.value;
        wx.setStorageSync('cartCount', cartProducts.length);//购物车商品数量
        app.checkCartCount();//设置购物车显示圆点
        //------------所有商品被选中状态置0 未选中
        for (let p = 0; p < cartProducts.length; p++) {
          cartProducts[p].isSelect = 0;
        }
        //---------------设置商品信息-------------------------------
        this.setData({
          cartProducts: cartProducts,
          isCheckedAll:false,
          selectNum:0
        })
      }else{
        if (res.msg == 'SessionTimeOut'){
          app.SessionTimeOut();
        }else{
          Util.showToast('加载失败，请稍后重试。',1000);
        }
      }
    }, true, '加载中');

  },

  selectAll: function(e) { //改变全选

    let cartProducts = this.data.cartProducts; //所有购物车商品
    let isCheckedAll = this.data.isCheckedAll; //是否是全选
    let totalCount = 0;
    let selectNum = 0;

    //-------------判断是否是编辑状态---------------------------
    let isEdit = this.data.isEdit;

    if (isCheckedAll) { //是否全选中状态 全选置0
      for (let p = 0; p < cartProducts.length; p++) {
        cartProducts[p].isSelect = 0;
      }
      isCheckedAll = false
      selectNum = 0;
    } else {
      if (isEdit) { //编辑状态 且为全未选中
        for (let p = 0; p < cartProducts.length; p++) {
          cartProducts[p].isSelect = 1

        }
        selectNum = cartProducts.length;
      } else { //非编辑状态 且为全未选中
        for (let p = 0; p < cartProducts.length; p++) {
          if (cartProducts[p].isValid == 1) { //有效改变商品状态
            cartProducts[p].isSelect = 1
            selectNum = selectNum + 1
          } else { //失效商品取消选中
            cartProducts[p].isSelect = 0
          }
        }
      }
      isCheckedAll = true
    }

    for (let p = 0; p < cartProducts.length; p++) {
      if (cartProducts[p].isValid == 1 && cartProducts[p].isSelect == 1) {
        totalCount = totalCount + parseFloat(cartProducts[p].count * cartProducts[p].price)
      }
    }

    console.log("selectNum" + selectNum);
    //更新商品数据及总额
    this.setData({
      cartProducts: cartProducts,
      totalCount: totalCount.toFixed(2),
      isCheckedAll: isCheckedAll,
      selectNum: selectNum
    })
  },
  editCart: function() { //编辑购物车
    //清空全选状态--------------------------------------


    let cartProducts = this.data.cartProducts;
    for (let i = 0; i < cartProducts.length; i++) {
      cartProducts[i].todo = '0';
    }
    this.setData({
      isEdit: true,
      isCheckedAll: this.data.isCheckedAll,
      cartProducts: cartProducts
    })
  },
  saveCart: function(e) { //完成编辑保存--交互

    let [selectNum, validNum] = [0, 0]; //已选中个数和有效商品个数
    let cartProducts = this.data.cartProducts; //购物车列表

    if (cartProducts.length > 0) {
      
      //console.log('编辑保存cartProducts', cartProducts);
      Http.postReq('/weixin/cart/updateCart', {
        todoList: JSON.stringify(cartProducts),
        rdSession: wx.getStorageSync('rd_session')
      }, (res) => {
        console.log('updateCart', res);
        if (res.ret) {
          //计算商品总额
          cartProducts = res.data.value;
          for (let p = 0; p < cartProducts.length; p++) {
            if (cartProducts[p].isSelect == 1) {
              selectNum = parseInt(selectNum) + 1
            }
            //长度已选中的
            if (cartProducts[p].isValid == 1) {
              validNum = parseInt(validNum) + 1;
            }
          }

          console.log(cartProducts);
          //更新商品数据
          this.setData({
            cartProducts: cartProducts,
            isCheckedAll: cartProducts.length == 0 ? false : selectNum == validNum ? true : false,
            selectNum: selectNum
          })
          console.log("编辑后商品长度" + this.data.cartProducts.length);
        } else {
          console.log('编辑失败');
        }
      }, true, '加载中');

    } else { //没有编辑的商品
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isSelect == 1 && cartProducts[p].isValid == 1) {
          selectNum = parseInt(selectNum) + 1
        }
        if (cartProducts[p].isValid == 0) { //失效商品不选
          cartProducts[p].isSelect = 0
        }
      }
    }
    console.log("selectNum" + selectNum);
    this.setData({
      isEdit: false,
      cartProducts: cartProducts,
      selectNum: selectNum
    })
  },

  minCount: function(e) {
    console.log("减少" + e);
    let count = e.currentTarget.dataset.count; //原购物车商品数量
    let index = e.currentTarget.dataset.index; //商品列表下标
    let cartProducts = this.data.cartProducts; //所有购物车商品

    if (count > 1) {
      count = parseInt(count) - 1;
    } else {
      count = 1;
      wx.showToast({
        title: '购买数量不能小于1',
        icon: 'none'
      })
    }
    //改变被选中商品数量
    cartProducts[index].count = count;

    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }

    //存储编辑商品(用于后台交互)---------------------------------

    //更新本地数据------------------------
    this.setData({
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts
    })

  },
  addCount: function(e) { //增加单个商品数量
    console.log("增加" + e);
    let count = e.currentTarget.dataset.count; //原购物车商品数量
    let index = e.currentTarget.dataset.index; //商品列表下标
    let cartProducts = this.data.cartProducts; //所有购物车商品
    let stock = cartProducts[index].stock; //当前商品库存
    let [msg, compareNum] = ['', '']; //用于比较的库存数量；
    if (cartProducts[index].isLimited == '1') {
      compareNum = cartProducts[index].canBuyNum;
      msg = '该商品为限购商品，您最多还可购买' + compareNum + "个"
    } else {
      compareNum = stock;
      msg = '商品库存不足';
    }
    if (count < compareNum) { //当前商品数量小于库存
      count = parseInt(count) + 1;
    } else {
      count = compareNum;
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    }
    //改变被选中商品数量
    cartProducts[index].count = count;
    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }

    //存储编辑商品(用于后台交互)---------------------------------


    //更新 编辑列表
    this.setData({
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts,

      compareNum: compareNum

    })
  },
  changeCount: function(e) {
    console.log("输入商品数量" + e.detail.value);
    let inputCount = e.detail.value; //输入商品数量
    let index = e.currentTarget.dataset.index; //商品列表下标
    let cartProducts = this.data.cartProducts; //所有购物车商品
    let stock = cartProducts[index].stock; //当前商品库存
    let [msg, compareNum] = ['', '']; //用于比较的库存数量；
    if (cartProducts[index].isLimited == '1') {
      compareNum = cartProducts[index].canBuyNum;
      msg = '该商品为限购商品，您最多还可购买' + compareNum + "个"
    } else {
      compareNum = stock;
      msg = '商品库存不足';
    }
    if (inputCount < 1) {
      inputCount = 1;
      wx.showToast({
        title: '商品数量最小为1',
        icon: 'none'
      })
    } else {
      if (inputCount > compareNum) {
        inputCount = compareNum;
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    }
    //改变被选中商品数量
    cartProducts[index].count = inputCount;
    //同步商品总额
    let totalCount = 0;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].isSelect == 1 && cartProducts[i].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[i].price * cartProducts[i].count);
      }
    }
    //存储编辑商品(用于后台交互)---------------------------------


    //更新 编辑列表
    this.setData({
      totalCount: totalCount.toFixed(2),
      cartProducts: cartProducts,
    })

  },

  radioSelect: function(e) { //选择单个商品操作
    console.log("选中单个商品下标" + e.currentTarget.dataset.index);
    //获取所选元素下标
    let index = e.currentTarget.dataset.index; //商品列表下标
    let cartProducts = this.data.cartProducts; //所有购物车商品
    let isEdit = this.data.isEdit; //是否是编辑状态
    let isCheckedAll = false; //初始化全选状态
    //编辑状态下的失效商品可以选中 参与计数selectnum

    //----------------改变按钮的被选中状态--------------------
    let isSelect = cartProducts[index].isSelect;


    //设置状态
    if (isSelect == 0) {
      cartProducts[index].isSelect = 1
    } else {
      cartProducts[index].isSelect = 0
    }
    //计算选中状态-------------------------------------------------------------------
    let selectNum = 0; //被选中商品的数量
    let disValidNum = 0; //未选中数量
    if (isEdit) { //编辑状态 失效商品可选 
      //对商品数量进行累计
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isSelect == 1) {
          selectNum = parseInt(selectNum) + 1;
        }
      }
      if (selectNum == cartProducts.length) {
        isCheckedAll = true;
      }
    } else { //未编辑状态  失效商品设置为 isSelect = 0 
      for (let p = 0; p < cartProducts.length; p++) {
        if (cartProducts[p].isValid == 0) { //失效商品不参与计算
          disValidNum = parseInt(disValidNum) + 1;
          cartProducts[p].isSelect = 0;
          continue;
        }
        if (cartProducts[p].isSelect == 1) {
          selectNum = parseInt(selectNum) + 1;
        }
      }
      if (selectNum == parseInt(cartProducts.length - disValidNum)) {
        isCheckedAll = true;
      }
    }

    // //更新商品数据
    this.setData({
      cartProducts: cartProducts
    })
    // //-------------根据是否是编编辑状态获取商品的总额以及改变商品被选状态
    let totalCount = 0;
    for (let p = 0; p < cartProducts.length; p++) {
      if (cartProducts[p].isSelect == 1 && cartProducts[p].isValid == 1) {
        totalCount = totalCount + parseFloat(cartProducts[p].price * cartProducts[p].count);
      }
    }

    // //变更改动的商品列表选中状态----------------------------------------------

    console.log("selectNum" + selectNum);

    this.setData({
      totalCount: totalCount.toFixed(2),
      isCheckedAll: isCheckedAll,
      selectNum: selectNum,

    })
  },

  deleteProducts: function(e) { //批量删除
    console.log("批量删除");
    let cartProducts = this.data.cartProducts; //所有购物车商品
    let deleteList = []; //剩余商品列表，选中删除列表
    wx.showModal({
      title: '',
      content: '确定要删除所选商品么？',
      cancelText: '我再想想',
      confirmText: '确定',
      success: (e)=> {
        if (e.confirm) {
          //选出被选中的待删除列表
          for (let p = 0; p < cartProducts.length; p++) {
            if (cartProducts[p].isSelect == 1) {
              deleteList.push(cartProducts[p]);
            }
          }
          console.log(deleteList);
          //将数组转换为字符串 接收
          let deleteListStr = JSON.stringify(deleteList);

          wx.request({
            url: app.data.baseUrl + '/weixin/cart/delete',
            data: {
              deleteList: deleteListStr,
              rdSession: wx.getStorageSync('rd_session')
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            method: 'POST',
            success: (res)=> {
              console.log(res);
              if (res.data.ret) {
                Util.showToast('删除成功',1000,'none',()=>{
                  //将删除的移除购物车列表 返回商品列表
                  let newList = res.data.data.value;
                  let [isCheckedAll, isEdit] = [this.data.isCheckedAll,this.data.isEdit]
                  if (newList.length == 0){
                    [isCheckedAll, isEdit] = [false, false]
                  }
                  this.setData({
                    cartProducts: newList,
                    totalCount: 0,
                    isEdit: isEdit,
                    isCheckedAll: isCheckedAll
                  })
                  if (newList.length == 0) {
                    wx.hideTabBarRedDot({
                      index: 1
                    })
                    wx.setStorageSync('cartCount', 0);
                  }
                })
              } else {
                if (res.data.msg = 'SessionTimeOut'){
                  app.SessionTimeOut();
                }else{
                  Util.showToast('删除失败:'+res.data.msg, 1000, 'none');
                }
              }
            }
          })
        }
      }
    })
  },

  toPayPage: function(e) { //(结算)提交订单

    app.toPayPage(this);
    setTimeout(()=> {
      this.setData({
        isCheckedAll: false,
        selectNum: 0,
        totalCount: 0
      })
    }, 500)
  },

  onPullDownRefresh: function() {
    this.showCartList();
    wx.stopPullDownRefresh()
  },
  getFormId: function(e) {
    console.log(e);
    app.getFormId(e);
  },
  //根据商品id 查商品详情
  selectProductById: function(e) {
    console.log('根据商品id 查商品详情参数');
    console.log(e);
    let productId = e.currentTarget.dataset.productid || this.data.productId;
    console.log(productId);
    this.setData({
      productId: productId,
      pageUrl: '/pages/product/product'
    })
    util.throttle(app.selectProductById, 500, this);
  },
})